import Vue from 'vue'
import VueRouter from 'vue-router'
import { Local } from "../common"
import { TOKEN, ROUTER_ACTIVE } from '../config/localConstant'
import { verifyToken } from "../config/data"
import { messageTip } from "../components/JS"
import Home from '../views/Home.vue'
// import testManager from "./testManager"
import userManager from "./userManager"
import authManager from "./authManager"
import goodsManager from "./goodsManager"
import orderManager from "./orderManager"
import dataStatistics from './dataStatistics'

Vue.use(VueRouter)
const routes = [
    {
        path: "/vue-manager",
        name: "home",
        component: Home,
        redirect: () => {
            return Local.get(ROUTER_ACTIVE).msg 
                ? Local.get(ROUTER_ACTIVE).msg 
                : {name: "userList"}
        } ,
        children: [
            // ...testManager,
            ...userManager, 
            ...authManager,
            ...goodsManager,
            ...orderManager,
            ...dataStatistics,
        ]
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('../components/Login')
    },
    {
        path: "/",
        redirect: {name: "home"}
    }
]

const router = new VueRouter({
    mode: "history",
    base: '/vue-manager',
    routes
})

// 每个路由，都需要检查 token，推荐使用全局路由守卫 beforeEach
router.beforeEach(async (to, from, next) => {
    const { msg } = Local.get(TOKEN)
    if(to.path === "/login") {
        if(msg) {
            let result = await verifyToken()
            if(!result.verify) {
                next()
            } else {
                next(from.path)
                messageTip({content: "已登录，请先退出..."})
            }
        } else {
            next()
            messageTip({content: "欢迎光临"})
        }
    } else {
        if(!msg) {
            next("/login")
        } else {
            let result = await verifyToken()
            if(result.verify) {
                next()
            } else {
                next("/login")
            }
        }
    }
})

export default router
